const express = require('express');
const router = express.Router();
const con = require('../db/mysql');
router.get('/', async (req, res) => {
    const { page, limit } = req.query;
    try {
        const result = await con.query(`SELECT * FROM menu ORDER BY id DESC LIMIT ${limit} OFFSET ${page * limit - limit};SELECT COUNT(*) AS total FROM menu`);
        if (result.length) {
            res.json({
                msg: "查询成功",
                code: 200,
                data: result[0],
                total: result[1][0].total
            });
        }
    } catch (error) {
        throw error;
    }
})
router.post("/", async (req, res) => {
    const { label, icon, path,parent } = req.body;
    try {
        const result = await con.query(`SELECT * FROM menu WHERE label=?`, label);
        if (result.length > 0) {
            res.json({
                msg: "存在重复角色名称",
                code: 500,
            })
            return;
        }
        const result2 = await con.query(`INSERT INTO menu (label,icon,path,parent) VALUES (?,?,?,?)`, [label, icon, path,parent]);
        if (result2.affectedRows === 1) {
            res.json({
                msg: "新增成功",
                code: 200,
            })
        } else {
            res.json({
                msg: "新增失败",
                code: 500,
            })
        }
    }
    catch (e) {
        throw e;
    }
})
router.delete('/:id', async (req, res) => {
    const { id } = req.params;
    try {
        const result = await con.query(`DELETE FROM menu WHERE id=?`, id);
        if (result.affectedRows === 1) {
            res.json({
                msg: "删除成功",
                code: 200,
            })
        } else {
            res.json({
                msg: "删除失败",
                code: 500,
            })
        }
    } catch (error) {
        throw error;
    }
})
router.put('/:id', async (req, res) => {
    const { id } = req.params;
    const { label, icon, path,parent } = req.body;
    try {
        const result2 = await con.query(`SELECT * FROM menu WHERE label=? AND id !=?`, [label,id]);
        if (result2.length > 0) {
            res.json({
                msg: "存在重复角色名称",
                code: 500,
            })
            return;
        }
        const result = await con.query(`UPDATE menu SET label=?,icon=?,path=?,parent=? WHERE id=?`, [label, icon, path,parent, id]);
        if (result.affectedRows === 1) {
            res.json({
                msg: "更新成功",
                code: 200,
            })
        } else {
            res.json({
                msg: "更新失败",
                code: 500,
            })
        }

    } catch (error) {
        throw error;
    }
})
module.exports = router;